package com.xxx.user.controller;

import com.github.pagehelper.PageInfo;
import com.xxx.base.utils.R;
import com.xxx.user.domain.User;
import com.xxx.user.query.UserQuery;
import com.xxx.user.service.impl.UserServiceImpl;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/user")
@Api(tags = "用户接口类")
public class UserController {
    @Autowired
    private UserServiceImpl userService;

    @GetMapping
    @ApiOperation(value = "查询所有")
    public R<List<User>> findAll() {
        List<User> userList = userService.findAll();
        return R.ok(userList);
    }

    @GetMapping("/{id}")
    @ApiOperation(value = "查询一个")
    public R<User> findOne(@PathVariable Long id) {
        User user = userService.findOne(id);
        return R.ok(user);
    }

    @PostMapping
    @ApiOperation(value = "分页查询")
    public R<PageInfo<User>> queryPage(@RequestBody UserQuery userQuery) {
        List<User> userList = userService.queryPage(userQuery);
        PageInfo<User> info = new PageInfo<>(userList);
        return R.ok(info);
    }

    @PutMapping
    @ApiOperation(value = "添加或修改")
    public R<Void> addOrUpdateUser(@RequestBody User user) {
        try {
            Long id = user.getId();
            if (id == null) {
                userService.addUser(user);
            } else {
                userService.updateUser(user);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return R.fail();
        }
        return R.ok();
    }

    @DeleteMapping("/{id}")
    @ApiOperation(value = "删除一个")
    public R<Void> delete(@PathVariable Long id) {
        try {
            userService.delete(id);
        } catch (Exception e) {
            e.printStackTrace();
            return R.fail();
        }
        return R.ok();
    }

    @PatchMapping
    @ApiOperation("批量删除")
    public R<Void> batchDeletes(@RequestBody Long[] ids) {
        try {
            userService.batchDeletes(ids);
        } catch (Exception e) {
            e.printStackTrace();
            return R.fail();
        }
        return R.ok();
    }
}
